from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter
from .models import SatelliteSchedule
from .serializers import SatelliteScheduleSerializer, SatelliteScheduleCreateSerializer


class SatelliteScheduleViewSet(viewsets.ModelViewSet):
    """
    卫星排程视图集
    """
    queryset = SatelliteSchedule.objects.all().select_related(
        'satellite__group__project'
    ).order_by('-updated_at')
    
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_fields = ['satellite', 'satellite__group', 'satellite__group__project']
    ordering_fields = ['created_at', 'updated_at']
    search_fields = ['satellite__name', 'satellite__group__name', 'satellite__group__project__name']
    
    def get_serializer_class(self):
        """根据操作类型选择序列化器"""
        if self.action == 'create':
            return SatelliteScheduleCreateSerializer
        return SatelliteScheduleSerializer
    
    @action(detail=False, methods=['get'])
    def by_satellite(self, request):
        """
        根据卫星ID获取排程信息
        """
        satellite_id = request.query_params.get('satellite_id')
        if not satellite_id:
            return Response(
                {'error': '请提供卫星ID参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            schedule = SatelliteSchedule.objects.select_related(
                'satellite__group__project'
            ).get(satellite_id=satellite_id)
            serializer = self.get_serializer(schedule)
            return Response(serializer.data)
        except SatelliteSchedule.DoesNotExist:
            return Response(
                {'error': '未找到该卫星的排程信息'}, 
                status=status.HTTP_404_NOT_FOUND
            )
    
    @action(detail=False, methods=['post'])
    def bulk_create_or_update(self, request):
        """
        批量创建或更新排程信息
        """
        schedules_data = request.data.get('schedules', [])
        start_date = request.data.get('startDate')  # 获取基准开始日期
        
        if not isinstance(schedules_data, list):
            return Response(
                {'error': '请提供排程数据列表'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        created_count = 0
        updated_count = 0
        errors = []
        
        for i, schedule_data in enumerate(schedules_data):
            satellite_id = schedule_data.get('satellite')
            if not satellite_id:
                errors.append(f'第{i+1}条记录缺少卫星ID')
                continue
            
            try:
                # 准备排程信息，包含基准开始日期
                schedule_info = schedule_data.get('schedule_info', {})
                if start_date:
                    schedule_info['startDate'] = start_date
                
                # 尝试获取现有记录
                schedule, created = SatelliteSchedule.objects.get_or_create(
                    satellite_id=satellite_id,
                    defaults={'schedule_info': schedule_info}
                )
                
                if created:
                    created_count += 1
                else:
                    # 更新现有记录
                    schedule.schedule_info = schedule_info
                    schedule.save()
                    updated_count += 1
                    
            except Exception as e:
                errors.append(f'第{i+1}条记录处理失败: {str(e)}')
        
        return Response({
            'message': f'处理完成，创建 {created_count} 条，更新 {updated_count} 条记录',
            'created_count': created_count,
            'updated_count': updated_count,
            'errors': errors
        })
    
    @action(detail=True, methods=['post'])
    def add_task(self, request, pk=None):
        """
        向排程中添加任务块
        """
        schedule = self.get_object()
        task_data = request.data.get('task')
        
        if not task_data:
            return Response(
                {'error': '请提供任务块数据'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 验证任务块数据
        required_fields = ['task_name', 'duration']
        for field in required_fields:
            if field not in task_data:
                return Response(
                    {'error': f'任务块缺少必需字段: {field}'}, 
                    status=status.HTTP_400_BAD_REQUEST
                )
        
        # 确保schedule_info是列表格式
        if not isinstance(schedule.schedule_info, list):
            schedule.schedule_info = []
        
        # 添加任务块
        schedule.schedule_info.append(task_data)
        schedule.save()
        
        serializer = self.get_serializer(schedule)
        return Response(serializer.data)
    
    @action(detail=True, methods=['delete'])
    def remove_task(self, request, pk=None):
        """
        从排程中移除任务块
        """
        schedule = self.get_object()
        task_index = request.data.get('task_index')
        
        if task_index is None:
            return Response(
                {'error': '请提供任务块索引'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        if not isinstance(schedule.schedule_info, list):
            return Response(
                {'error': '排程信息格式错误'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            task_index = int(task_index)
            if 0 <= task_index < len(schedule.schedule_info):
                removed_task = schedule.schedule_info.pop(task_index)
                schedule.save()
                
                serializer = self.get_serializer(schedule)
                return Response({
                    'message': f'已移除任务块: {removed_task.get("task_name", "未知任务")}',
                    'schedule': serializer.data
                })
            else:
                return Response(
                    {'error': '任务块索引超出范围'}, 
                    status=status.HTTP_400_BAD_REQUEST
                )
        except ValueError:
            return Response(
                {'error': '任务块索引必须是整数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
    
    @action(detail=False, methods=['delete'], url_path='delete_by_satellite/(?P<satellite_id>[^/.]+)')
    def delete_by_satellite(self, request, satellite_id=None):
        """
        删除指定卫星的所有排程记录
        """
        print(f"[DEBUG] 接收到删除请求，satellite_id: {satellite_id}")
        
        if not satellite_id:
            return Response(
                {'error': '请提供卫星ID'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            # 先查看数据库中有哪些记录
            existing_records = SatelliteSchedule.objects.filter(satellite=satellite_id)
            print(f"[DEBUG] 查找到的记录数量: {existing_records.count()}")
            for record in existing_records:
                print(f"[DEBUG] 记录ID: {record.id}, 卫星ID: {record.satellite.id}, 卫星名称: {record.satellite.name}")
            
            # 查找并删除指定卫星的所有排程记录
            deleted_count, _ = SatelliteSchedule.objects.filter(satellite=satellite_id).delete()
            print(f"[DEBUG] 实际删除的记录数量: {deleted_count}")
            
            if deleted_count > 0:
                return Response({
                    'success': True,
                    'message': f'成功删除卫星 {satellite_id} 的 {deleted_count} 条排程记录',
                    'deleted_count': deleted_count
                })
            else:
                return Response({
                    'success': True,
                    'message': f'卫星 {satellite_id} 没有找到排程记录',
                    'deleted_count': 0
                })
        except Exception as e:
            print(f"[DEBUG] 删除过程中发生异常: {str(e)}")
            return Response(
                {'error': f'删除排程记录时发生错误: {str(e)}'}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
